import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'models/unified_config.dart';
import 'services/config_service.dart';

class AIBuildSuggestionsPage extends StatefulWidget {
  final Function(int)? onNavigateToPage;

  const AIBuildSuggestionsPage({super.key, this.onNavigateToPage});

  @override
  State<AIBuildSuggestionsPage> createState() => _AIBuildSuggestionsPageState();
}

class _AIBuildSuggestionsPageState extends State<AIBuildSuggestionsPage> {
  final TextEditingController _pythonFileController = TextEditingController();
  String _analysisResult = '';
  bool _isAnalyzing = false;
  List<String> _suggestions = [];
  UnifiedConfig? _suggestedConfig;

  @override
  void dispose() {
    _pythonFileController.dispose();
    super.dispose();
  }

  // 选择Python文件
  Future<void> _selectPythonFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['py'],
        dialogTitle: '选择Python文件',
      );

      if (result != null && result.files.single.path != null) {
        setState(() {
          _pythonFileController.text = result.files.single.path!;
        });
      }
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('文件选择失败: $e')));
    }
  }

  // 分析Python文件并获取AI建议
  Future<void> _analyzeWithAI() async {
    if (_pythonFileController.text.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请先选择或输入Python文件路径')));
      return;
    }

    setState(() {
      _isAnalyzing = true;
      _analysisResult = '';
      _suggestions.clear();
    });

    try {
      // 读取Python文件内容
      final file = File(_pythonFileController.text);
      if (!await file.exists()) {
        throw Exception('文件不存在');
      }

      final content = await file.readAsString();

      // 调用AI分析功能
      await _performAIAnalysis(content);
    } catch (e) {
      setState(() {
        _analysisResult = '分析失败: $e';
      });
    } finally {
      setState(() {
        _isAnalyzing = false;
      });
    }
  }

  // 执行AI分析（增强版智能分析）
  Future<void> _performAIAnalysis(String pythonContent) async {
    setState(() {
      _analysisResult = '🔍 正在进行深度代码分析...\n';
    });

    // 综合分析
    final analysisData = await _performComprehensiveAnalysis(pythonContent);

    setState(() {
      _analysisResult += '📊 分析完成！\n\n';
      _analysisResult += '=== 📋 详细分析报告 ===\n';
      _analysisResult +=
          '导入模块 (${analysisData['imports'].length}个): ${analysisData['imports'].take(8).join(', ')}${analysisData['imports'].length > 8 ? '...' : ''}\n';
      _analysisResult += 'GUI框架: ${analysisData['guiFramework'] ?? '无'}\n';
      _analysisResult +=
          '代码复杂度: ${analysisData['complexity']} (${analysisData['codeLines']}行有效代码)\n';
      _analysisResult += '项目类型: ${analysisData['projectType']}\n';
      _analysisResult += '依赖风险等级: ${analysisData['dependencyRisk']}\n';
      _analysisResult += '性能敏感度: ${analysisData['performanceSensitivity']}\n\n';
    });

    // 生成智能建议配置
    _suggestedConfig = _generateIntelligentConfig(analysisData);

    // 生成详细建议列表
    _suggestions = _generateDetailedSuggestions(analysisData);

    setState(() {
      _analysisResult += '=== 🎯 AI智能建议 ===\n';
      for (int i = 0; i < _suggestions.length; i++) {
        _analysisResult += '${i + 1}. ${_suggestions[i]}\n';
      }

      _analysisResult += '\n=== ⚙️ 推荐配置摘要 ===\n';
      _analysisResult +=
          '构建模式: ${_getBuildModeDescription(_suggestedConfig!.buildMode)}\n';
      _analysisResult +=
          '优化级别: ${_getOptimizationDescription(_suggestedConfig!.optimization)}\n';
      _analysisResult +=
          '控制台: ${_suggestedConfig!.disableConsole ? '禁用' : '启用'}\n';
      _analysisResult +=
          'LTO优化: ${_suggestedConfig!.enableLto ? '启用' : '禁用'}\n';
      if (_suggestedConfig!.customDependencies.isNotEmpty) {
        _analysisResult +=
            '检测依赖: ${_suggestedConfig!.customDependencies.join(', ')}\n';
      }
    });
  }

  // 综合分析Python文件（增强版）
  Future<Map<String, dynamic>> _performComprehensiveAnalysis(
    String content,
  ) async {
    final imports = _extractImports(content);
    final guiFramework = _detectGuiFramework(content);
    final complexity = _analyzeComplexity(content);
    final projectType = _detectProjectType(content, imports);
    final dependencyRisk = _assessDependencyRisk(imports);
    final performanceSensitivity = _analyzePerformanceSensitivity(
      content,
      imports,
    );
    final codeLines = _countEffectiveLines(content);

    return {
      'imports': imports,
      'guiFramework': guiFramework,
      'complexity': complexity,
      'projectType': projectType,
      'dependencyRisk': dependencyRisk,
      'performanceSensitivity': performanceSensitivity,
      'codeLines': codeLines,
      'content': content, // 确保包含文件内容
    };
  }

  // 提取Python文件中的导入模块（增强版）
  List<String> _extractImports(String content) {
    final imports = <String>[];
    final lines = content.split('\n');

    for (final line in lines) {
      final trimmed = line.trim();
      if (trimmed.startsWith('import ')) {
        final parts = trimmed.substring(7).split(',');
        for (final part in parts) {
          final module = part.trim().split(' ')[0].split('.')[0];
          if (module.isNotEmpty) imports.add(module);
        }
      } else if (trimmed.startsWith('from ')) {
        final parts = trimmed.split(' ');
        if (parts.length >= 2) {
          final module = parts[1].split('.')[0];
          if (module.isNotEmpty) imports.add(module);
        }
      }
    }

    return imports.toSet().toList();
  }

  // 计算有效代码行数
  int _countEffectiveLines(String content) {
    return content.split('\n').where((line) {
      final trimmed = line.trim();
      return trimmed.isNotEmpty &&
          !trimmed.startsWith('#') &&
          !trimmed.startsWith('"""') &&
          !trimmed.startsWith("'''");
    }).length;
  }

  // 检测项目类型
  String _detectProjectType(String content, List<String> imports) {
    if (imports.any(
      (imp) =>
          ['flask', 'django', 'fastapi', 'tornado'].contains(imp.toLowerCase()),
    )) {
      return 'Web应用';
    }
    if (imports.any(
      (imp) => [
        'tkinter',
        'PyQt5',
        'PyQt6',
        'PySide2',
        'PySide6',
        'kivy',
      ].contains(imp.toLowerCase()),
    )) {
      return 'GUI桌面应用';
    }
    if (imports.any(
      (imp) => [
        'numpy',
        'pandas',
        'scipy',
        'matplotlib',
        'seaborn',
      ].contains(imp.toLowerCase()),
    )) {
      return '数据科学/分析';
    }
    if (imports.any(
      (imp) => [
        'tensorflow',
        'torch',
        'keras',
        'sklearn',
      ].contains(imp.toLowerCase()),
    )) {
      return '机器学习/AI';
    }
    if (imports.any(
      (imp) => ['requests', 'urllib', 'aiohttp'].contains(imp.toLowerCase()),
    )) {
      return '网络工具';
    }
    if (content.contains('if __name__ == "__main__"')) {
      return '命令行工具';
    }
    return '通用脚本';
  }

  // 评估依赖风险等级
  String _assessDependencyRisk(List<String> imports) {
    final highRiskModules = ['tensorflow', 'torch', 'opencv', 'PyQt5', 'PyQt6'];
    final mediumRiskModules = [
      'numpy',
      'pandas',
      'matplotlib',
      'scipy',
      'pillow',
    ];

    final highRiskCount = imports
        .where(
          (imp) => highRiskModules.any(
            (risk) => imp.toLowerCase().contains(risk.toLowerCase()),
          ),
        )
        .length;
    final mediumRiskCount = imports
        .where(
          (imp) => mediumRiskModules.any(
            (risk) => imp.toLowerCase().contains(risk.toLowerCase()),
          ),
        )
        .length;

    if (highRiskCount > 0) return '高 (${highRiskCount}个复杂依赖)';
    if (mediumRiskCount > 2) return '中 (${mediumRiskCount}个中等依赖)';
    return '低';
  }

  // 分析性能敏感度
  String _analyzePerformanceSensitivity(String content, List<String> imports) {
    final performanceKeywords = [
      'numpy',
      'pandas',
      'tensorflow',
      'torch',
      'opencv',
      'scipy',
    ];

    // 修复正则表达式，正确转义特殊字符
    final computePatterns = [
      r'for.*in.*range',
      r'while.*:',
      r'\.apply\(',
      r'\.map\(',
      r'\.groupby\(',
      r'\.transform\(',
    ];

    final hasPerformanceLibs = imports.any(
      (imp) => performanceKeywords.any(
        (keyword) => imp.toLowerCase().contains(keyword.toLowerCase()),
      ),
    );

    // 使用try-catch包装正则表达式匹配，避免格式错误
    bool hasComputePatterns = false;
    try {
      hasComputePatterns = computePatterns.any(
        (pattern) => RegExp(pattern).hasMatch(content),
      );
    } catch (e) {
      // 如果正则表达式失败，使用简单字符串匹配作为后备
      hasComputePatterns =
          content.contains('.apply(') ||
          content.contains('.map(') ||
          content.contains('for ') ||
          content.contains('while ');
    }

    if (hasPerformanceLibs && hasComputePatterns) return '高 (计算密集型)';
    if (hasPerformanceLibs || hasComputePatterns) return '中';
    return '低';
  }

  // 检测GUI框架（增强版）
  String? _detectGuiFramework(String content) {
    final guiFrameworks = {
      'import tkinter': 'Tkinter',
      'from tkinter': 'Tkinter',
      'import PyQt5': 'PyQt5',
      'from PyQt5': 'PyQt5',
      'import PyQt6': 'PyQt6',
      'from PyQt6': 'PyQt6',
      'import PySide2': 'PySide2',
      'from PySide2': 'PySide2',
      'import PySide6': 'PySide6',
      'from PySide6': 'PySide6',
      'import wx': 'wxPython',
      'from wx': 'wxPython',
      'import kivy': 'Kivy',
      'from kivy': 'Kivy',
      'import flet': 'Flet',
      'from flet': 'Flet',
      'import streamlit': 'Streamlit',
      'from streamlit': 'Streamlit',
      'import gradio': 'Gradio',
      'from gradio': 'Gradio',
    };

    for (final entry in guiFrameworks.entries) {
      if (content.contains(entry.key)) {
        return entry.value;
      }
    }
    return null;
  }

  // 智能配置生成（增强版）
  UnifiedConfig _generateIntelligentConfig(Map<String, dynamic> analysisData) {
    final config = UnifiedConfig();
    final imports = analysisData['imports'] as List<String>;
    final complexity = analysisData['complexity'] as String;
    final projectType = analysisData['projectType'] as String;
    final dependencyRisk = analysisData['dependencyRisk'] as String;
    final performanceSensitivity =
        analysisData['performanceSensitivity'] as String;
    final hasGui =
        analysisData['guiFramework'] != null &&
        analysisData['guiFramework'] != '无';
    final String content = analysisData['content'] as String? ?? '';

    // 智能选择构建模式
    if (projectType == 'Web应用' || dependencyRisk.startsWith('高')) {
      config.buildMode = BuildMode.standalone;
    } else if (complexity == '简单' && !dependencyRisk.startsWith('高')) {
      config.buildMode = BuildMode.onefile;
    } else {
      config.buildMode = BuildMode.standalone;
    }

    // 智能优化级别选择
    if (performanceSensitivity.startsWith('高')) {
      config.optimization = OptimizationLevel.advanced;
      config.enableLto = true;
    } else if (complexity == '复杂' || dependencyRisk.startsWith('高')) {
      config.optimization = OptimizationLevel.basic;
      config.enableLto = false;
    } else {
      config.optimization = OptimizationLevel.advanced;
      config.enableLto = false;
    }

    // 智能控制台配置 - 检测GUI和控制台输出
    final bool hasPrint =
        content.contains('print(') ||
        content.contains('print ') ||
        content.contains('input(') ||
        content.contains('sys.stdout') ||
        content.contains('sys.stderr');

    // 调试信息
    print('DEBUG AI Analysis:');
    print('  guiFramework: ${analysisData['guiFramework']}');
    print('  hasGui: $hasGui');
    print('  hasPrint: $hasPrint');
    print('  content contains print(: ${content.contains('print(')}');
    print('  disableConsole will be: ${hasGui && !hasPrint}');

    // 只有纯GUI应用（无控制台输出）才禁用控制台
    config.disableConsole = hasGui && !hasPrint;

    // 智能依赖检测
    final detectedDeps = <String>[];
    final commonPackages = {
      'numpy': 'numpy',
      'pandas': 'pandas',
      'requests': 'requests',
      'matplotlib': 'matplotlib',
      'scipy': 'scipy',
      'pillow': 'pillow',
      'opencv': 'opencv-python',
      'flask': 'flask',
      'django': 'django',
      'fastapi': 'fastapi',
    };

    for (final imp in imports) {
      final lowerImp = imp.toLowerCase();
      for (final entry in commonPackages.entries) {
        if (lowerImp.contains(entry.key)) {
          detectedDeps.add(entry.value);
        }
      }
    }

    config.customDependencies = detectedDeps.toSet().toList();

    return config;
  }

  // 生成详细建议（增强版）
  List<String> _generateDetailedSuggestions(Map<String, dynamic> analysisData) {
    final suggestions = <String>[];
    final imports = analysisData['imports'] as List<String>;
    final complexity = analysisData['complexity'] as String;
    final projectType = analysisData['projectType'] as String;
    final dependencyRisk = analysisData['dependencyRisk'] as String;
    final performanceSensitivity =
        analysisData['performanceSensitivity'] as String;
    final guiFramework = analysisData['guiFramework'] as String?;

    // 构建模式建议
    if (projectType == 'Web应用') {
      suggestions.add('🌐 Web应用建议使用Standalone模式，便于部署和调试');
    } else if (complexity == '简单' && !dependencyRisk.startsWith('高')) {
      suggestions.add('📦 简单项目建议使用Onefile模式，生成单个可执行文件');
    } else {
      suggestions.add('📁 复杂项目建议使用Standalone模式，便于管理依赖');
    }

    // 智能控制台建议 - 根据GUI和print语句综合判断
    final String fileContent = analysisData['content'] as String? ?? '';
    final bool hasPrint =
        fileContent.contains('print(') ||
        fileContent.contains('print ') ||
        fileContent.contains('input(');

    if (guiFramework != null && guiFramework != '无') {
      // 有GUI框架的情况
      if (hasPrint) {
        suggestions.add('🖥️ 检测到$guiFramework框架但包含控制台输出，建议保留控制台窗口');
        suggestions.add('💡 如需隐藏控制台，建议将print改为日志文件输出');
      } else {
        suggestions.add('🖥️ 检测到纯$guiFramework应用，建议禁用控制台窗口');
      }

      suggestions.add('🎨 建议添加应用图标和版本信息提升用户体验');

      if (guiFramework.contains('Qt')) {
        suggestions.add('⚡ Qt应用建议启用相关插件优化');
      }
    } else {
      // 没有GUI框架的情况
      if (hasPrint) {
        suggestions.add('🖥️ 控制台应用包含输出语句，建议保留控制台窗口');
      } else {
        suggestions.add('🖥️ 无GUI无输出的脚本，可考虑禁用控制台');
      }
    }

    // 性能优化建议
    if (performanceSensitivity.startsWith('高')) {
      suggestions.add('🚀 计算密集型应用建议启用完全优化和LTO');
      suggestions.add('💾 建议启用内存优化选项');
    } else if (performanceSensitivity.startsWith('中')) {
      suggestions.add('⚖️ 建议平衡优化级别和编译时间');
    }

    // 依赖风险建议
    if (dependencyRisk.startsWith('高')) {
      suggestions.add('⚠️ 检测到复杂依赖，建议使用基础优化避免兼容性问题');
      suggestions.add('🔧 建议手动测试所有功能模块');
    }

    // 项目类型特定建议
    switch (projectType) {
      case '数据科学/分析':
        suggestions.add('📊 数据科学项目建议包含NumPy/Pandas相关优化');
        break;
      case '机器学习/AI':
        suggestions.add('🤖 AI项目建议检查模型文件和权重包含');
        break;
      case '网络工具':
        suggestions.add('🌐 网络应用建议包含SSL证书和网络库');
        break;
    }

    // 通用建议
    if (imports.contains('requests') || imports.contains('urllib')) {
      suggestions.add('🔒 网络请求应用建议包含SSL证书');
    }

    if (complexity == '复杂') {
      suggestions.add('🧪 复杂项目建议先进行小规模测试构建');
    }

    return suggestions;
  }

  // 获取构建模式描述
  String _getBuildModeDescription(BuildMode mode) {
    switch (mode) {
      case BuildMode.onefile:
        return 'Onefile (单文件模式)';
      case BuildMode.standalone:
        return 'Standalone (独立目录模式)';
      case BuildMode.module:
        return 'Module (模块模式)';
    }
  }

  // 获取优化级别描述
  String _getOptimizationDescription(OptimizationLevel level) {
    switch (level) {
      case OptimizationLevel.none:
        return 'None (无优化)';
      case OptimizationLevel.basic:
        return 'Basic (基础优化)';
      case OptimizationLevel.advanced:
        return 'Full (完全优化)';
    }
  }

  // 分析代码复杂度
  String _analyzeComplexity(String content) {
    final lines = content
        .split('\n')
        .where((line) => line.trim().isNotEmpty)
        .length;
    if (lines < 50) return '简单';
    if (lines < 200) return '中等';
    return '复杂';
  }

  // 生成建议配置
  UnifiedConfig _generateSuggestedConfig(
    List<String> imports,
    bool hasGui,
    String complexity,
    String content,
  ) {
    final config = UnifiedConfig();

    // 根据复杂度选择构建模式
    if (complexity == '简单') {
      config.buildMode = BuildMode.onefile;
    } else {
      config.buildMode = BuildMode.standalone;
    }

    // 智能控制台设置 - 检测print输出
    final bool hasPrint =
        content.contains('print(') ||
        content.contains('print ') ||
        content.contains('input(');

    // 只有在有GUI且没有print输出时才禁用控制台
    // 如果没有GUI但有print，应该保留控制台
    config.disableConsole = hasGui && !hasPrint;

    // 根据复杂度设置优化级别
    switch (complexity) {
      case '简单':
        config.optimization = OptimizationLevel.basic;
        break;
      case '中等':
        config.optimization = OptimizationLevel.advanced;
        break;
      case '复杂':
        config.optimization = OptimizationLevel.basic;
        config.enableLto = true;
        break;
    }

    // 添加检测到的依赖
    config.customDependencies = imports
        .where(
          (imp) => [
            'numpy',
            'pandas',
            'requests',
            'matplotlib',
            'scipy',
            'pillow',
            'opencv',
          ].contains(imp.toLowerCase()),
        )
        .toList();

    return config;
  }

  // 生成建议列表
  List<String> _generateSuggestions(
    List<String> imports,
    bool hasGui,
    String complexity,
  ) {
    final suggestions = <String>[];

    // 构建模式建议
    if (complexity == '简单') {
      suggestions.add('建议使用 Onefile 模式，生成单个可执行文件');
    } else {
      suggestions.add('建议使用 Standalone 模式，便于调试和分发');
    }

    // GUI相关建议
    if (hasGui) {
      suggestions.add('检测到GUI框架，建议禁用控制台窗口');
      suggestions.add('建议添加应用图标以提升用户体验');
    } else {
      suggestions.add('控制台应用，保持控制台窗口显示');
    }

    // 依赖建议
    if (imports.contains('numpy') || imports.contains('pandas')) {
      suggestions.add('检测到科学计算库，建议启用相关插件优化');
    }

    if (imports.contains('requests') || imports.contains('urllib')) {
      suggestions.add('检测到网络请求，建议包含SSL证书');
    }

    // 优化建议
    if (complexity == '复杂') {
      suggestions.add('复杂项目建议启用LTO优化以减小文件大小');
      suggestions.add('建议使用基础优化级别以平衡编译时间和性能');
    } else {
      suggestions.add('建议使用完全优化以获得最佳性能');
    }

    return suggestions;
  }

  // 应用建议配置
  Future<void> _applySuggestedConfig() async {
    if (_suggestedConfig == null) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请先进行AI分析生成建议配置')));
      return;
    }

    if (_pythonFileController.text.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('请先选择Python文件')));
      return;
    }

    try {
      // 确保Python文件路径正确设置
      String pythonFilePath = _pythonFileController.text.trim();
      if (pythonFilePath.isNotEmpty) {
        _suggestedConfig!.projectPath = pythonFilePath;

        // 自动设置输出目录为文件所在目录
        final directory = pythonFilePath.substring(
          0,
          pythonFilePath.lastIndexOf('\\'),
        );
        _suggestedConfig!.outputDir = directory;
        print('DEBUG: Auto-set output directory from AI config: $directory');
      }

      // 保存配置
      final configService = await ConfigService.getInstance();
      await configService.saveUnifiedConfig(_suggestedConfig!);

      // 直接切换到项目配置页面
      if (mounted && widget.onNavigateToPage != null) {
        // 通知父组件切换到项目设置页面
        widget.onNavigateToPage!(1); // 使用索引导航到项目设置页面
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const Icon(Icons.error, color: Colors.white),
              const SizedBox(width: 8),
              Expanded(child: Text('应用配置失败: $e')),
            ],
          ),
          backgroundColor: Colors.red.shade600,
          duration: const Duration(seconds: 4),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Scaffold(
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 页面标题
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Colors.purple.shade400, Colors.purple.shade600],
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Icon(
                    Icons.psychology,
                    color: Colors.white,
                    size: 32,
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Text(
                    'AI构建建议',
                    style: theme.textTheme.headlineMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                      color: theme.colorScheme.primary,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              '上传Python文件，获取智能构建建议和最佳配置推荐',
              style: theme.textTheme.bodyLarge?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 32),

            // 文件选择区域
            Card(
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                Colors.blue.shade400,
                                Colors.blue.shade600,
                              ],
                            ),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: const Icon(
                            Icons.file_upload,
                            color: Colors.white,
                            size: 20,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            'Python文件选择',
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: TextFormField(
                            controller: _pythonFileController,
                            decoration: const InputDecoration(
                              labelText: 'Python文件路径',
                              hintText: '输入.py文件的完整路径',
                              border: OutlineInputBorder(),
                              prefixIcon: Icon(Icons.code),
                            ),
                          ),
                        ),
                        const SizedBox(width: 12),
                        FilledButton(
                          onPressed: _selectPythonFile,
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                width: 20,
                                height: 20,
                                decoration: BoxDecoration(
                                  gradient: LinearGradient(
                                    colors: [
                                      Colors.orange.shade400,
                                      Colors.orange.shade600,
                                    ],
                                  ),
                                  borderRadius: BorderRadius.circular(4),
                                ),
                                child: const Icon(
                                  Icons.folder_open,
                                  color: Colors.white,
                                  size: 14,
                                ),
                              ),
                              const SizedBox(width: 6),
                              const Text('浏览'),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    SizedBox(
                      width: double.infinity,
                      child: FilledButton(
                        onPressed: _isAnalyzing ? null : _analyzeWithAI,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            if (_isAnalyzing)
                              const SizedBox(
                                width: 16,
                                height: 16,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                ),
                              )
                            else
                              Container(
                                width: 24,
                                height: 24,
                                decoration: BoxDecoration(
                                  gradient: LinearGradient(
                                    colors: [
                                      Colors.blue.shade400,
                                      Colors.blue.shade600,
                                    ],
                                  ),
                                  borderRadius: BorderRadius.circular(6),
                                ),
                                child: const Icon(
                                  Icons.auto_awesome,
                                  color: Colors.white,
                                  size: 16,
                                ),
                              ),
                            const SizedBox(width: 8),
                            Text(_isAnalyzing ? '分析中...' : '开始AI分析'),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),

            // 分析结果区域
            if (_analysisResult.isNotEmpty) ...[
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(20.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [
                                  Colors.green.shade400,
                                  Colors.green.shade600,
                                ],
                              ),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: const Icon(
                              Icons.analytics,
                              color: Colors.white,
                              size: 20,
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              '分析结果',
                              style: theme.textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          if (_suggestedConfig != null)
                            FilledButton(
                              onPressed: _applySuggestedConfig,
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Container(
                                    width: 24,
                                    height: 24,
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        colors: [
                                          Colors.green.shade400,
                                          Colors.green.shade600,
                                        ],
                                      ),
                                      borderRadius: BorderRadius.circular(6),
                                    ),
                                    child: const Icon(
                                      Icons.check,
                                      color: Colors.white,
                                      size: 16,
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  const Text('应用到项目配置'),
                                ],
                              ),
                            ),
                        ],
                      ),
                      const SizedBox(height: 16),
                      Container(
                        width: double.infinity,
                        constraints: const BoxConstraints(
                          maxHeight: 400, // 限制最大高度
                        ),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: theme.colorScheme.surfaceVariant.withOpacity(
                            0.3,
                          ),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: theme.colorScheme.outline.withOpacity(0.2),
                          ),
                        ),
                        child: SingleChildScrollView(
                          child: SelectableText(
                            _analysisResult,
                            style: theme.textTheme.bodyMedium?.copyWith(
                              fontFamily: 'monospace',
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
            const SizedBox(height: 24), // 底部间距
          ],
        ),
      ),
    );
  }
}
